<?php

//开放api接口
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use App\Exceptions\BasicException;
use App\Response\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class OpenApiController extends BaseController
{
    /**
     * @api {Get} /OpenApi/getUnionUsers 查询关联用户信息，根据设备和ip
     * @apiGroup 开放api
     *
     * @apiParam {Int} user_no 用户号，3个参数不能同时为空
     * @apiParam {Int} user_name 用户姓名
     * @apiParam {Int} alipay_account 支付宝账号
     *
     * @apiSuccessExample {json} Response-Example
     * {
     * "code": 200,
     * "data": [
     * {
     * "user_id": 642655,
     * "user_no": "347022", 用户号
     * "mobile": "15675501002", 手机号
     * "register_time": "2020-06-03 19:31:13", 注册时间
     * "three_party": 1, 第三方注册方式：0：手机号；1：微信；2：QQ；3：h5
     * "three_party_name": "微信", 第三方注册方式名称
     * "nickname": "有没有那么", 昵称
     * "head_picture": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/ios_images/2020-06-03/DD8031A3-9E48-48D2-B8C3-3FF87D30575C.png", 头像
     * "recharge_total": 0 历史累计充值金额，单位：元
     * },
     * {
     * "user_id": 565687,
     * "user_no": "340072",
     * "mobile": "18301597298",
     * "register_time": "2020-03-13 22:40:20",
     * "three_party": 0,
     * "three_party_name": "",
     * "nickname": "左冷",
     * "head_picture": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/android_images/565687/20200326110503_1585191903421483.jpg",
     * "recharge_total": 0
     * }
     * ]
     * }
     */
    public function getUnionUsers(Request $request)
    {
        $userNo = $request->user_no;
        $userName = $request->user_name;
        $alipayAccount = $request->alipay_account;

        if (empty($userNo) && empty($userName) && empty($alipayAccount)) {
            throw new BasicException(0, '用户编号、姓名、支付宝账号不能同时为空');
        }

        $returnArr = ['union_device_users' => [], 'union_ip_users' => []];
        $userIds = [];
        if ($userNo) {
            $userId = app('model_user_code')->select('user_id')->where('user_code', $userNo)->value('user_id');
            if ($userId) {
                $userIds[] = $userId;
            } else {
                return $returnArr;
            }
        }
        if ($userName) {
            $userId = app('model_user_auth')->getFieldValue('user_id', ['full_name' => $userName, 'app_status' => 1, 'deleted' => 0]);
            if ($userId) {
                $userIds[] = $userId;
            } else {
                return $returnArr;
            }
        }
        if ($alipayAccount) {
            $userId = app('model_user_bank')->getFieldValue('user_id', ['bank_num' => $alipayAccount, 'bank_type' => 1]);
            if ($userId) {
                $userIds[] = $userId;
            } else {
                return $returnArr;
            }
        }
        if (count($userIds) != count(array_unique($userIds))) {
            return $returnArr;
        }

        $deviceUsers = static::getData($userIds[0], 'device_id');
        $ipUses = static::getData($userIds[0], 'ip');

        return Response::sendData(['union_device_users' => $deviceUsers, 'union_ip_users' => $ipUses]);
    }

    private function getData($userId, $keyword)
    {
        $deviceIds = $this->getDeviceIdsByUserId($userId, $keyword);
        $userIds = $this->getUserIdsByKeyword($deviceIds, $keyword);
        //查询用户
        $users = $this->getUsers($userIds);
        //查询用户数据
        $userDatas = $this->getUserDatas($userIds);
        $userDatas = array_column($userDatas, null, 'user_id');
        //查询充值用户
        $rechargeUsers = $this->getRechargeUsers($userIds);
        //查询用户姓名
        $userNames = $this->getUserNames($userIds);
        //查询用户支付宝账号
        $alipayAccounts = $this->getAlipayAccounts($userIds);

        foreach ($users as &$user) {
            //昵称和头像
            if (isset($userDatas[$user->user_id])) {
                $user->nickname = $userDatas[$user->user_id]['nickname'];
                $user->head_picture = $userDatas[$user->user_id]['head_picture'];
            } else {
                $user->nickname = '';
                $user->head_picture = '';
            }
            //充值金额
            if (isset($rechargeUsers[$user->user_id])) {
                $user->recharge_total = $rechargeUsers[$user->user_id];
            } else {
                $user->recharge_total = 0;
            }
            //姓名
            if (isset($userNames[$user->user_id])) {
                $user->user_name = $userNames[$user->user_id];
            } else {
                $user->user_name = '';
            }
            //支付宝账号
            if (isset($alipayAccounts[$user->user_id])) {
                $user->alipay_account = $alipayAccounts[$user->user_id];
            } else {
                $user->alipay_account = '';
            }
            //第三方注册方式
            if ($user->three_party == 1) {
                $user->three_party_name = '微信';
            } else if ($user->three_party == 2) {
                $user->three_party_name = 'QQ';
            } else {
                $user->three_party_name = '';
            }
        }
        return $users;
    }

    //根据用户id获取所有设备id
    private function getDeviceIdsByUserId($userId, $keyword)
    {
        return app('model_user_device')->where('user_id', $userId)->groupBy($keyword)->pluck($keyword);
    }

    //根据所有设备id获取所有用户id
    private function getUserIdsByKeyword($deviceIds, $keyword)
    {
        return app('model_user_device')->whereIn($keyword, $deviceIds)->groupBy('user_id')->pluck('user_id');
    }

    //查询用户
    private function getUsers($userIds)
    {
        return app('model_user')
            ->select(DB::raw('user_id, user_no, FROM_UNIXTIME(register_time) as register_time, mobile, three_party'))
            ->whereIn('user_id', $userIds)
            ->where('deleted', 0)
            ->get();
    }

    //查询用户数据
    private function getUserDatas($userIds)
    {
        return app('model_user_data')
            ->select('user_id', 'nickname', 'head_picture')
            ->whereIn('user_id', $userIds)
            ->get()->toArray();
    }

    //查询充值用户
    private function getRechargeUsers($userIds)
    {
        return app('model_user_recharge')
            ->select(DB::raw("SUM(money) as money, user_id"))
            ->whereIn('user_id', $userIds)
            ->where('status', 2)
            ->groupBy('user_id')
            ->pluck('money', 'user_id');
    }

    //查询用户真实姓名
    private function getUserNames($userIds)
    {
        return app('model_user_auth')
            ->whereIn('user_id', $userIds)
            ->where('app_status', 1)
            ->where('deleted', 0)
            ->pluck('full_name', 'user_id');
    }

    //查询用户支付宝账号
    private function getAlipayAccounts($userIds)
    {
        return app('model_user_bank')
            ->whereIn('user_id', $userIds)
            ->where('bank_type', 1)
            ->pluck('bank_num', 'user_id');
    }

    /**
     * @api {Get} /OpenApi/getDayDataStatistics 查询日数据统计
     *
     * @apiGroup 开放api
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": [
    {
    "id": 11,
    "date": "2021-05-07", 日期
    "register_total": 33, 注册用户数
    "recharge_total": "43.00", 充值金额
    "serial_total": 546 流水，礼物金币
    },
    {
    "id": 10,
    "date": "2021-05-31",
    "register_total": 0,
    "recharge_total": "0.00",
    "serial_total": 0
    },
    {
    "id": 9,
    "date": "2021-06-01",
    "register_total": 0,
    "recharge_total": "0.00",
    "serial_total": 0
    },
    {
    "id": 12,
    "date": "2021-06-02",
    "register_total": 10200,
    "recharge_total": "15313134.00",
    "serial_total": 654654432
    }
    ]
    }
     */
    public function getDayDataStatistics(Request $request)
    {
        $token = $request->header('token');
        if ($token != app('model_config')->where('key', 'DATA_STATISTICS_API_TOKEN')->value('value')) {
            throw new BasicException(0, '非法请求');
        }
        $date = date('Y-m-d', strtotime("-30 day"));
        $list = app('model_everyday_data_statistics')->where('date', '>=', $date)->orderBy('date', 'asc')->get()->toArray();

        $start = $request->input("start","2022-01-01");
        $total = app('repo_data_statistics')->calcTotalStat($start);
        return Response::sendData([
            'list'  =>  $list,
            'total' =>  $total,
        ]);
    }

    public function getHash(Request $request)
    {
        $pwd = $request->pwd;
        return Response::sendData(Hash::make($pwd));
    }
}
